package com.yunxi.rocketmq.producer;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.Producer;
import com.aliyun.openservices.ons.api.SendResult;
import com.yunxi.rocketmq.config.RocketMQConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * Created by Administrator on 2019/6/16.
 */
@Component
public class EaiLogsProducer {
    private static final Logger logger = LoggerFactory.getLogger(EaiLogsProducer.class);
    @Autowired
    private RocketMQConfig rocketMQConfig;
    @Value("${aliyun.rocketMQ.eai.log.topic}")
    private String topic;
    @Value("${aliyun.rocketMQ.eai.log.tag}")
    private String tag;

    /**
     * 普通消息
     * 单向（Oneway）发送
     *
     * @param msg
     * @return
     */
    public boolean sendMessage(String msg) {
        Producer producer = rocketMQConfig.getProducer();
        try {
            Message message = new Message(topic, tag, msg.getBytes());
            // 由于在 oneway 方式发送消息时没有请求应答处理，一旦出现消息发送失败，则会因为没有重试而导致数据丢失。
            SendResult result = producer.send(message);
            System.out.println(result);
            logger.info(JSONObject.toJSONString(result));
            //producer.sendOneway(message);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

}
